package com.lagou.edu.server;

import java.io.File;
import java.io.IOException;
import java.net.Socket;

/**
 * @author 胡益文
 * @since 2021/10/9 11:33
 */
public class HttpServletProcessor extends Thread{

    private Socket accept;
    private Mapper mapper;


    public HttpServletProcessor(Socket accept, Mapper mapper) {
        this.accept = accept;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            Request request = new Request(accept.getInputStream());
            Response response = new Response(accept.getOutputStream());
            //request.getUrl()
            String url = request.getUrl();
            String host = request.getHost();
            if(!mapper.hosts.containsKey(host)&&host.indexOf("127.0.0.1")>-1){
                host = host.replace("127.0.0.1","localhost");
            } else if(!mapper.hosts.containsKey(host)&&host.indexOf("localhost")>-1){
                host = host.replace("localhost","127.0.0.1");
            }
            String context = "";
            if(url.lastIndexOf("/")>1){
                context = url.substring(url.indexOf("/")+1, url.indexOf("/", 1));
            }
            System.out.println("");

            //定位Host
            Mapper.MappedHost mappedHost = mapper.hosts.get(host);
            if(mappedHost==null){
                response.output(HttpProtocolUtil.getHttpHeader404());
            }
            //定位Context
            Mapper.MappedContext mappedContext = mappedHost.contexts.get(context);
            if(mappedContext==null){
                response.output(HttpProtocolUtil.getHttpHeader404());
            }
            String contextUrl = url.replace("/" + context , "");
            //定位Wrapper（Serlvet）
            Mapper.MappedWrapper mappedWrapper = mappedContext.wrappers.get(contextUrl);
            if(mappedWrapper==null){
                if(new File(mappedContext.object.getContextPath()+contextUrl).exists()){
                    response.outputHtml(mappedContext.object.getContextPath()+contextUrl);
                } else {
                    response.output(HttpProtocolUtil.getHttpHeader404());
                }
              
            }else{
                if( mappedWrapper.object.httpServlet!=null){
                    mappedWrapper.object.httpServlet.service(request,response);
                }else{
                    response.output(HttpProtocolUtil.getHttpHeader404());
                }

            }
            System.out.println("Tst1");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
